package com.sion.difytest;

import android.util.Log;

import androidx.annotation.NonNull;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class LLMWorkflowApi {
    private static final String BASE_URL = "https://api.dify.ai/v1";
    //    private static final String API_KEY = "app-XPVVg88gUGEj37EC0jmPYkJa";
    private static final String API_KEY = "";

    private static final String USER_ID = "user_123";
    private LLMApi.OnAnswerReceivedListener listener;

    public void setReceivedListener(LLMApi.OnAnswerReceivedListener listener) {
        this.listener = listener;
    }

    public void sendMessage(String query) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(120, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS)
                .build();

        String url = BASE_URL + "/chat-messages";
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        String jsonPayload = "{\"query\": \"" + query + "\", \"response_mode\": \"streaming\", \"user\": \"" + USER_ID + "\", \"inputs\": {}, \"files\": []}";
        RequestBody body = RequestBody.create(JSON, jsonPayload);

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                if (listener != null) {
                    listener.onFailure("请求异常: " + e.getMessage());
                }
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                    try {
                        JSONObject errorData = new JSONObject(response.body().string());
                        String errorMessage = errorData.optString("message", "请求失败");
                        if (listener != null) {
                            listener.onFailure(errorMessage);
                        }
                    } catch (JSONException e) {
                        if (listener != null) {
                            listener.onFailure("请求失败");
                        }
                    }
                    return;
                }

                ResponseBody responseBody = response.body();
                if (responseBody != null) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody.byteStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("data: ")) {
                            String eventData = line.substring(6).trim();
                            if (eventData.equals("[DONE]")) {
                                break;
                            }
                            try {
                                JSONObject event = new JSONObject(eventData);
                                String eventType = event.optString("event");
                                if ("message".equals(eventType)) {
                                    String answer = event.optString("answer", "");
                                    if (listener != null) {
                                        listener.onAnswerReceived(answer);
                                    }
                                }
                            } catch (JSONException e) {
                                Log.e("LLMWorkflowApi", "无效的 JSON 事件: " + eventData);
                            }
                        }
                    }
                }
            }
        });
    }
}